package com.example.administrator.im.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.im.R;
import com.example.administrator.im.db.FriendDBHelper;
import com.example.administrator.im.db.GroupDBHelper;
import com.example.administrator.im.interfacz.ItemTouchMoveListener;
import com.example.administrator.im.json.ResultJson;
import com.example.administrator.im.utils.DialogUtils;
import com.example.administrator.im.utils.HttpUtils;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * create:2018/9/28 21:51
 * author: 姚鸿杰
 **/
public class LinkmanManagerAdapter extends RecyclerView.Adapter<LinkmanManagerAdapter.Holder> implements ItemTouchMoveListener {

    private List<String> mList;
    private Context mContext;
    private final String TAG = "LinkmanManagerAdapter";

    private boolean firstMove = false;
    private int flag;


    private final int MOVE_SUCCESS = 1;
    private final int MOVE_FAIL = 0;

    public LinkmanManagerAdapter(List<String> mList, Context mContext) {
        this.mList = mList;
        this.mContext = mContext;
    }

    public void addGroup(String name) {
        mList.add(name);
        notifyDataSetChanged();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case MOVE_FAIL:
                    notifyItemChanged(msg.arg1);
                    break;
                case MOVE_SUCCESS:
                    int position = msg.arg1;
                    //移除分组
                    mList.remove(position);
                    notifyItemRemoved(position);
                    if (position != mList.size()) {
                        notifyItemRangeChanged(position, mList.size() - position);
                    }
                    break;
            }
        }
    };

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.recycler_linkman_manage, viewGroup, false);
        return new Holder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        holder.tv_name.setText(mList.get(position));
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public class Holder extends RecyclerView.ViewHolder {

        private TextView tv_name;

        public Holder(@NonNull View itemView) {
            super(itemView);

            tv_name = (TextView) itemView.findViewById(R.id.tv_gourp_name);
        }
    }

    @Override
    public boolean onItemMove(final int fromPosition, final int toPosition, boolean isRun) {

        if (!firstMove) {
            firstMove = true;
            flag = fromPosition;
        }

        if (!isRun) {
            //1.数据交换 2.刷新
            Collections.swap(mList, fromPosition, toPosition);
            notifyItemMoved(fromPosition, toPosition);

        } else {
            HttpUtils.moveGroupRequest(fromPosition, toPosition, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                    //提示连接超时

                    DialogUtils.clearAlerDialog();
                    firstMove = false;
                    Log.e(TAG, e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    DialogUtils.clearAlerDialog();
                    firstMove = false;
                    String content = response.body().string();
                    Gson gson = new Gson();
                    ResultJson json = gson.fromJson(content, ResultJson.class);
                    if (json.getCode() == HttpUtils.SUCCESS) {


                        //更新数据
                        GroupDBHelper group_from = LitePal.where("position = ?", String.valueOf(flag)).findFirst(GroupDBHelper.class);
                        if (flag < toPosition) {
                            for (int i = flag + 1; i <= toPosition; i++) {   //交换中间数据
                                moveData(i, i - 1);
                            }
                        } else if (flag > toPosition) {
                            for (int i = flag - 1; i >= toPosition; i--) {   //交换中间数据
                                moveData(i, i + 1);
                            }
                        }
                        //交换边界数据
                        group_from.setPosition(toPosition);
                        group_from.save();

                    }

                }
            });

        }

        return true;
    }

    public void moveData(int from, int to) {
        GroupDBHelper group = LitePal.where("position = ?",
                String.valueOf(from)).findFirst(GroupDBHelper.class);
        group.setPosition(to);
        group.save();
    }

    @Override
    public boolean onItemRemove(final int position) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext)
                .setTitle("联系人管理")
                .setMessage("移除分组会将联系人移动至默认分组")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        boolean default_group = LitePal.where("position = ?",
                                String.valueOf(position)).findFirst(GroupDBHelper.class).isDefault_group();

                        if (default_group) {
                            Toast.makeText(mContext, "默认分组不可移除!!!", Toast.LENGTH_SHORT).show();
                            //关闭加载
                            DialogUtils.clearAlerDialog();
                            notifyItemChanged(position);
                            return;
                        }

                        //移除web端
                        HttpUtils.deleteGroupRequest(position, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                                //提示连接超时
                                Log.e(TAG, e.getMessage());
                                DialogUtils.clearAlerDialog();
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                //关闭加载
                                DialogUtils.clearAlerDialog();

                                String content = response.body().string();
                                Gson gson = new Gson();
                                ResultJson json = gson.fromJson(content, ResultJson.class);
                                if (json.getCode() == HttpUtils.SUCCESS) {

                                    Message msg = new Message();
                                    msg.arg1 = position;
                                    msg.what = MOVE_SUCCESS;
                                    handler.sendMessage(msg);

                                    //移除数据库
                                    GroupDBHelper groupDBHelper = LitePal.where("position = ?",
                                            String.valueOf(position)).findFirst(GroupDBHelper.class);
                                    int id = groupDBHelper.getId();
                                    groupDBHelper.delete();

                                    //比该序号大的分组都减1
                                    List<GroupDBHelper> groups = LitePal.where("position > ?",
                                            String.valueOf(position)).find(GroupDBHelper.class);
                                    if (groups.size() > 0) {
                                        for (GroupDBHelper group : groups) {
                                            int group_position = group.getPosition();
                                            group.setPosition(group_position - 1);
                                            group.save();
                                        }
                                    }

                                    //将联系人移动至默认分组
                                    int group_id = LitePal.where("default_group = ?",
                                            String.valueOf(1)).findFirst(GroupDBHelper.class).getId();
                                    //获取所有联系人
                                    List<FriendDBHelper> friends =
                                            LitePal.where("group_id = ?", String.valueOf(id)).find(FriendDBHelper.class);
                                    for (int i = 0; i < friends.size(); i++) {
                                        friends.get(i).setGroup_id(group_id);
                                        friends.get(i).save();
                                    }


                                } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                                    //提示移除失败
                                    Message msg = new Message();
                                    msg.arg1 = position;
                                    msg.what = MOVE_FAIL;
                                    handler.sendMessage(msg);
                                    Log.e(TAG, json.getData().toString());
                                }
                            }
                        });
                    }
                })
                .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DialogUtils.clearAlerDialog();
                        notifyItemChanged(position);
                    }
                });
        builder.create();
        builder.show();

        return true;
    }
}
